package com.example.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Web层相关的实用工具类
 * 
 * @author 
 * @date 2011-12-1 下午3:14:59
 */
public class WebUtils {
	/**
	 * 将请求参数封装为Map<br>
	 * request中的参数t1=1&t1=2&t2=3<br>
	 * 形成的map结构：<br>
	 * key=t1;value[0]=1,value[1]=2<br>
	 * key=t2;value[0]=3<br>
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static HashMap<String, String> getPraramsAsMap(HttpServletRequest request) {
		HashMap<String, String> hashMap = new HashMap<String, String>();
		Map map = request.getParameterMap();
		Iterator keyIterator = (Iterator) map.keySet().iterator();
		while (keyIterator.hasNext()) {
			String key = (String) keyIterator.next();
			String value = ((String[]) (map.get(key)))[0];
			hashMap.put(key, value);
		}
		return hashMap;
	}
	/**
	 * 查询条件非法字符过滤
	 * @param str
	 * @return
	 */
	public static String filterCondition(String str){
		str = str.replaceAll("\\\\","\\\\\\\\");
		str = str.replaceAll("%","\\\\%");
		str = str.replaceAll("_","\\\\_");
		str = str.replaceAll("'","''");
		return str;
	}
	
	/**
	 * 返回data
	 * @param success
	 * @param errmsg
	 * @param rs
	 * @return
	 */
	public static String getData(boolean success,String errmsg,Object rs) {
		Map map = new HashMap();
		map.put("success", success);
		map.put("errmsg", errmsg);
		map.put("rs", rs);
		//json.accumulate("success", success);
		//json.accumulate("errmsg", errmsg);
		//json.accumulate("rs",rs);
		return JSON.toJSONString(map,SerializerFeature.WriteNullStringAsEmpty);
	}
	
	
	/**
	 * 按要求截取并拼接字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String subString(String str,int len) {
		if (str != null && str.length() > len) {// 超出len，截去len-2，后面用...表示
			str = str.substring(0, len-2) + "…";
		}
		return str;
	}
	
	/**
	 * 过滤html标签和style标签
	 * 
	 * @param inputString
	 * @return
	 */
	public static String Html2Text(String inputString){
		   //过滤html标签
		   String htmlStr = inputString; // 含html标签的字符串
		   String textStr = "";
		   Pattern p_script;
		   java.util.regex.Matcher m_script;
		   Pattern p_style;
		   java.util.regex.Matcher m_style;
		   Pattern p_html;
		   java.util.regex.Matcher m_html;
		   Pattern p_cont1;
		   java.util.regex.Matcher m_cont1;
		   Pattern p_cont2;
		   java.util.regex.Matcher m_cont2;
		   try {
		    String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
		    // }
		    String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
		    // }
		    String regEx_html = "<[.[^<]]*>|&\\w+;"; // 定义HTML标签的正则表达式
		   // String regEx_cont1 = "[\\d+\\s*`~!@#$%^&*\\(\\)\\+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘：”“’_]"; // 定义HTML标签的正则表达式
		    //String regEx_cont2 = "[\\w[^\\W]*]"; // 定义HTML标签的正则表达式[a-zA-Z]
		    p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		    m_script = p_script.matcher(htmlStr);
		    htmlStr = m_script.replaceAll(""); // 过滤script标签
		    p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		    m_style = p_style.matcher(htmlStr);
		    htmlStr = m_style.replaceAll(""); // 过滤style标签
		    p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		    m_html = p_html.matcher(htmlStr);
		    htmlStr = m_html.replaceAll(""); // 过滤html标签
		    //p_cont1 = Pattern.compile(regEx_cont1, Pattern.CASE_INSENSITIVE);
		    //m_cont1 = p_cont1.matcher(htmlStr);
		    //htmlStr = m_cont1.replaceAll(""); // 过滤其它标签
		    //p_cont2 = Pattern.compile(regEx_cont2, Pattern.CASE_INSENSITIVE);
		    //m_cont2 = p_cont2.matcher(htmlStr);
		    //htmlStr = m_cont2.replaceAll(""); // 过滤html标签
		    textStr = htmlStr;
		   } catch (Exception e) {
		    System.err.println("Html2Text: " + e.getMessage());
		   }
		   return textStr;// 返回文本字符串
	}
	
	/**
	 * 按指定长度截取字符串数组
	 * @param str
	 * @param len
	 * @return
	 */
	public static String[] strSubToArr(String str, int len) {
		int total_len = str.length();
		String[] arr_content = null;
		int size = 0;
		int pos = 0;
		if (total_len % len == 0) {
			size = total_len / len;
		} else {
			size = total_len / len + 1;
		}
		arr_content = new String[size];
		if (total_len < len) {
			arr_content[0] = str;
		} else {
			int end_len = len;
			for (int i = 0; i < size; i++) {
				if (end_len > total_len) {
					arr_content[i] = str.substring(pos);
				} else {
					arr_content[i] = str.substring(pos, end_len);
					pos = end_len;
					end_len = len * (i + 2);
				}
			}
		}
		return arr_content;
	}
	
	public static boolean isNull(String str) {
		if(null == str || str.equals("null") || str.equals("")){
			return true;
		}else{
			return false;
		}
	}
	
	 /**把本地或服务器地址置空
     */
    public static String replaceAllImageUrlAndHeadPicUrl(String content,String imageUrl,String headPicUrl,String tmpUrl,String realUrl){
    	if(content==null || content.equals("")){
    		return "";
    	}
    	//System.out.println("content111==="+content);
    	content = content.replaceAll(imageUrl, "");
    	content = content.replaceAll(headPicUrl, "");
    	content = content.replaceAll(tmpUrl,realUrl);
    	//System.out.println("content222==="+content);
		return content;
    }
     
    /**编辑器内容里把相对路径的图片替换成全路径
     */
    public static String replaceAllByHeadPicUrl(String content,String realUrl,String headPicUrl){
    	if(content==null || content.equals("")){
    		return "";
    	}
    	//System.out.println("content111==="+content);
    	content = content.replaceAll("<img\\s+src=\""+realUrl+"", "<img src=\""+headPicUrl+realUrl);
    	//content = content.replaceAll("<img\\s+src=\"/resources/upload", "<img src=\""+headPicUrl+"/resources/upload");
    	//System.out.println("content222==="+content);
		return content;
    }
     
    
    /*普通图片绝对路径转访问路径
     */
    public static String addHeadPicUrl(String pic,String headPicUrl){
    	if(pic==null || pic.equals("")){
    		return "";
    	}
    	//System.out.println("content111==="+content);
    	pic = headPicUrl+ pic;
		return pic;
    }
    
	/**
	 * 返回Map
	 * @return
	 */
	public static Map getResMap(String jsonString) {
		Map<String, Object> resMap= new HashMap<String, Object>();
		JSONObject jsonMap = JSONObject.parseObject(jsonString);
	    for(String key :jsonMap.keySet()){
	    	resMap.put(key, jsonMap.get(key).toString());
	    }
	    return resMap;
	}


	/**
	 * 判断字符串是否为空或空字符或undefined
	 * @param str
	 * @return
	 */
	public static Boolean isNotBlank(String str) {
		if (StringUtils.isEmpty(str) || str.equals("undefined")) {
			return false;
		}
		return true;
	}

	public static Boolean isBlank(String str) {
		if (StringUtils.isEmpty(str) || str.equals("undefined")) {
			return true;
		}
		return false;
	}
}
